<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\QrCodeController;
use App\Http\Controllers\Wechat\AppletAuthController;
use App\Models\ResourceBusinessName;
use App\Models\ResourceLeer;
use App\Models\ResourceTotal;
use App\Validate\ResourceTotalValidate;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 数字资源总数据管理(对外资源)
 */
class ResourceTotalController extends CommonController
{
    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->validate = new ResourceTotalValidate();
        $this->model = new ResourceTotal();
    }




    /**
     * 筛选(用于下拉框选择)
     * @param keywords 检索条件
     * @param resource_business_id 资源商id
     * @param big_type_id 系统大类  （系统内定，不可修改）
     */
    public function filterList()
    {
        $keywords = $this->request->input('keywords', '');
        $resource_business_id = $this->request->input('resource_business_id', '');
        $big_type_id = $this->request->input('big_type_id', '');
        $limit = $this->request->input('limit', 10);

        $res = $this->model->getFilterLists(['guid', 'title', 'isbn'], $keywords, $resource_business_id, $big_type_id, $limit);

        if ($res) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }


    /**
     * 检索 mysql 数据 （全数据检索）
     * @param keywords 检索条件
     * @param resource_business_id 资源商id
     * @param big_type_id 系统大类  （系统内定，不可修改）
    // * @param type_id 系统小类
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function lists()
    {
        $keywords = $this->request->input('keywords', '');
        $resource_business_id = $this->request->input('resource_business_id', '');
        $big_type_id = $this->request->input('big_type_id', '');
        $limit = $this->request->input('limit', 10);
        $page = $this->request->input('page', 1);
        $res = $this->model->lists($keywords, $resource_business_id, $big_type_id, null, null, null, null, null, null, null, null, $limit);

        if ($res['data']) {
            $resourceBusinessNameModel = new ResourceBusinessName();
            foreach ($res['data'] as $key => $val) {
                //增加序号
                $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
                $res['data'][$key]['resource_business_name'] = $resourceBusinessNameModel->where('id', $val['resource_business_id'])->where('is_del', 1)->value('name');
                $res['data'][$key]['big_type_name'] = !empty($val['con_big_type']) ? $val['con_big_type']['type_name'] : '';
                unset($res['data'][$key]['con_big_type']);
            }
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }

        return $this->returnApi(203, '暂无数据');
    }


    /**
     * 获取资源详情
     * @param guid  资源guid
     * @param resource_business_id  资源商id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //$res = $this->model->detail($this->request->resource_business_id, null, $this->request->guid);
        $res = $this->model->detail(null, null, $this->request->guid); //这里不能传资源商id，传了有问题
        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }

        $data = $res->toArray();
        $data['type_name'] = !empty($data['con_type']) ? $data['con_type']['type_name'] : '';
        $data['big_type_name'] = !empty($data['con_big_type']) ? $data['con_big_type']['type_name'] : '';
        //获取资源商名称
        $data['resource_business_name'] = ResourceBusinessName::where('id', $data['resource_business_id'])->where('is_del', 1)->value('name');
        unset($data['con_type']);
        unset($data['con_big_type']);
        if ($this->request->resource_business_id == 5) {
            //增加返回资源链接
            $data['link'] = ResourceLeer::where('guid', $data['guid'])->where('is_del', 1)->value('link');
        }

        //生成资源二维码
        $resourceTotalModel = new ResourceTotal();
        $qrCodeObj = new QrCodeController();
        $qrCodeAppletObj = new AppletAuthController();

        if (config('other.project_type') == 'wechat') {
            $qr_code = $resourceTotalModel->getWechatResourceQrUrl($data['big_type_id'], $data['guid'], $data['resource_business_id']);
            $qr_url = $qrCodeObj->setQr($qr_code, false, 300, 1);
            $data['qr_url'] = $qr_url ? $qr_url : null;
            $data['applet_qr_url'] = null;
        } else {
            //生成二维码
            $qr_code = $resourceTotalModel->getResourceQrUrl($data['big_type_id'], $data['guid']);
            $qr_url = $qrCodeObj->setQr($qr_code, false, 300, 1);
            $data['qr_url'] = $qr_url ? $qr_url : null;

            //生成二维码（小程序二维码）
            $resource_id = $this->getResourceEncryptId($data['id'], 10);
            // Log::error('生成小程序id:'.$resource_id);

            $applet_qr_code = $data['big_type_id'] . '-' . $resource_id; //不能使用guid，因为guid为32位，scene 只能为32，所以采用id加密形式处理
            $applet_save_addr = 'temp_qr/' . uniqid() . date('ymdhis') . '.png'; //存放在临时路径
            $applet_qr_url_res = $qrCodeAppletObj->getAppletQrCode($applet_qr_code, public_path('uploads') . '/' . $applet_save_addr);
            $data['applet_qr_url'] = $applet_qr_url_res ? $applet_save_addr : null;
        }

        return $this->returnApi(200, "获取成功", true, $data);
    }


    /**
     * 删除
     * @param guid  资源guid
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $guid = $this->request->guid;
        $res = $this->model->where('guid', $guid)->where('is_del', 1)->first();
        if (!$res) {
            return $this->returnApi(201, '参数传递错误');
        }

        DB::beginTransaction();
        try {
            $res->is_del = 2;
            $res->save();
            //删除各自文件的资源
            $model = $this->model->getResourceTotalModel($res->resource_business_id);
            if (empty($model)) {
                throw new \Exception('单个资源商未找到');
            }
            $result = $model->where('guid', $guid)->where('is_del', 1)->update(['is_del' => 2, 'change_time' => date('Y-m-d H:i:s')]);
            if (!$result) {
                throw new \Exception('删除失败');
            }
            DB::commit();
            return $this->returnApi(200, '删除成功', true);
        } catch (\Exception $e) {
            DB::rollback();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 推荐与取消推荐
     * @param guids  资源guid 多个逗号拼接
     * @param is_recom  1 推荐  2 取消推荐
     */
    public function recomAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('recom_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $guids = $this->request->guids;
        $is_recom = $this->request->is_recom;
        DB::beginTransaction();
        try {
            $msg = $is_recom == 1 ? '推荐' : '取消推荐';
            $guid_arr = explode(',', $guids);
            foreach ($guid_arr as $guid) {
                $res = $this->model->where('guid', $guid)->where('is_del', 1)->first();
                if (!$res) {
                    continue;
                }
                $res->is_recom = $is_recom;
                $res->save();
                //删除各自文件的资源
                $model = $this->model->getResourceTotalModel($res->resource_business_id);
                if (empty($model)) {
                    throw new \Exception('单个资源商未找到');
                }
                $result = $model->where('guid', $guid)->where('is_del', 1)->update(['is_recom' => $is_recom, 'change_time' => date('Y-m-d H:i:s')]);
                if (!$result) {
                    throw new \Exception($msg . '失败');
                }
            }
            DB::commit();
            return $this->returnApi(200, $msg . '成功', true);
        } catch (\Exception $e) {
            DB::rollback();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
